from django.contrib.auth.models import Group
from rest_framework.permissions import BasePermission

class TeacherPermission(BasePermission):
    """
    老师权限：只有老师才能操作
    """

    def has_permission(self, request, view):
        user=request.user
        # 拿到老师组
        group = Group.objects.get(name='老师组')
        # 获取用户所在的组
        groups = user.groups.all()

        return bool(user.is_superuser or group in groups)



class ActiveUserPermission(BasePermission):
    """
    当前登录用户只能操作当前的用户相关功能
    """
    def has_permission(self, request, view):
        user = request.user
        # 当前登录用户的id：user.id 想要操作的用户的id
        return user.id ==int(view.kwargs['pk'])


class MyBasePermission(BasePermission):
    def has_permission(self, request, view): # 查权限
        if request.method in ['GET','HEAD','OPTION']:
            return True

        if request.user.is_superuser: # 超级用户e
            return True


        if view.action in ['create'or 'update']:
        # if view.action == 'create'or view.action =='update':
            user = request.user
            group =Group.objects.filter(name='老师组').first()
            groups = user.groups.all() # 获取用户多个身份
            return user.is_superuser or group in groups # 判断用户是否超级用户或者在这个组里面

        if view.action == 'destroy':  # 删除权限只能是管理员
            return request.user.is_superuser

def auto_user(func):
    def f(self,request,*args,**kwargs):
        request.POST._mutable = True
        request.data['user'] = str(request.user.id)
        return func(self,request,*args,**kwargs)
    return f

